<template>
  <div class="app-container">
    <!-- 学校搜索栏 -->
    <el-form :inline="true" label-width="90px" class="filter-bar" style="margin-bottom: 12px;">
      <el-form-item label="学校名称">
        <el-select v-model="queryParams.school" placeholder="选择学校" filterable clearable style="width: 240px">
          <el-option v-for="school in schoolOptions" :key="school.id" :label="school.title" :value="school.title"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getAnalysisBySchool">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="analysis-card">
            <div slot="header" class="card-header"><span>题型分析</span></div>
            <div ref="questionTypeChart" style="height: 400px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="analysis-card">
            <div slot="header" class="card-header"><span>分数分布</span></div>
            <div ref="scoreChart" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>

</template>

<script>
import { listSchool } from "@/api/system/school"
import { listStatisticsAnswer } from "@/api/system/answer"
import * as echarts from "echarts"

export default {
  name: "AnswerCharts",
  data() {
    return {
      loading: false,
      schoolOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        school: null
      },
      analysisData: {
        questionTypeStats: [],
        scoreDistribution: []
      }
    }
  },
  created() {
    listSchool({ pageNum: 1, pageSize: 1000000 }).then(response => {
      this.schoolOptions = response.rows
    })
    this.getAnalysisBySchool()
  },
  methods: {
    resetSearch() {
      this.queryParams.school = null
      this.getAnalysisBySchool()
    },
    async getAnalysisBySchool() {
      if (this.queryParams.school == null) {
        listSchool({pageNum: 1, pageSize: 1000000}).then(async response => {
          this.schoolOptions = response.rows
          this.queryParams.school = this.schoolOptions[0].title
          this.loading = true
          try {
            const resp = await listStatisticsAnswer(this.queryParams)
            const rows = resp.rows || []
            this.analysisData.questionTypeStats = this.aggregateClassificationStats(rows)
            this.analysisData.scoreDistribution = this.buildScoreDistribution(rows)
            this.$nextTick(() => this.initCharts())
          } finally {
            this.loading = false
          }
        })
      } else {
        this.loading = true
        try {
          const resp = await listStatisticsAnswer(this.queryParams)
          const rows = resp.rows || []
          this.analysisData.questionTypeStats = this.aggregateClassificationStats(rows)
          this.analysisData.scoreDistribution = this.buildScoreDistribution(rows)
          this.$nextTick(() => this.initCharts())
        } finally {
          this.loading = false
        }
      }



      // this.loading = true
      // try {
      //   const resp = await listStatisticsAnswer(this.queryParams)
      //   const rows = resp.rows || []
      //   this.analysisData.questionTypeStats = this.aggregateClassificationStats(rows)
      //   this.analysisData.scoreDistribution = this.buildScoreDistribution(rows)
      //   this.$nextTick(() => this.initCharts())
      // } finally {
      //   this.loading = false
      // }
    },
    aggregateClassificationStats(rows) {
      const map = new Map()
      rows.forEach(r => {
        const arr = r.classificationStatistics || []
        arr.forEach(it => {
          const name = it.name || '未分类'
          const prev = map.get(name) || { name, count: 0, totalScore: 0, dictSort: typeof it.dictSort !== 'undefined' ? Number(it.dictSort) : 9999 }
          prev.count += Number(it.count || 0)
          prev.totalScore += Number(it.totalScore || 0)
          map.set(name, prev)
        })
      })
      const stats = Array.from(map.values())
      stats.sort((a, b) => (a.dictSort || 0) - (b.dictSort || 0) || String(a.name).localeCompare(String(b.name)))
      return stats
    },
    buildScoreDistribution(rows) {
      const buckets = [
        { range: '0-59', count: 0 },
        { range: '60-69', count: 0 },
        { range: '70-79', count: 0 },
        { range: '80-89', count: 0 },
        { range: '90-100', count: 0 }
      ]
      rows.forEach(r => {
        const s = Number(r.score || 0)
        if (s < 60) buckets[0].count++
        else if (s < 70) buckets[1].count++
        else if (s < 80) buckets[2].count++
        else if (s < 90) buckets[3].count++
        else buckets[4].count++
      })
      return buckets
    },
    initCharts() {
      this.initQuestionTypeChart()
      this.initScoreChart()
    },
    initQuestionTypeChart() {
      const chart = echarts.init(this.$refs.questionTypeChart)
      const data = this.analysisData.questionTypeStats || []
      const avgData = data.map(item => {
        const c = Number(item.count || 0)
        const t = Number(item.totalScore || 0)
        return c > 0 ? Number((t / c).toFixed(2)) : 0
      })
      const option = {
        title: { text: '题型统计', left: 'center' },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['题目数量', '总分', '平均分'], top: 30 },
        xAxis: { type: 'category', data: data.map(item => item.name) },
        yAxis: [
          { type: 'value', name: '题目数量', position: 'left' },
          { type: 'value', name: '总分', position: 'right' }
        ],
        series: [
          { name: '题目数量', type: 'bar', data: data.map(item => item.count), itemStyle: { color: '#409EFF' } },
          { name: '总分', type: 'line', yAxisIndex: 1, data: data.map(item => item.totalScore), itemStyle: { color: '#67C23A' } },
          { name: '平均分', type: 'line', yAxisIndex: 1, data: avgData, itemStyle: { color: '#F56C6C' } }
        ]
      }
      chart.setOption(option)
    },
    initScoreChart() {
      const chart = echarts.init(this.$refs.scoreChart)
      const data = this.analysisData.scoreDistribution || []
      const option = {
        title: { text: '分数分布', left: 'center' },
        tooltip: { trigger: 'item' },
        xAxis: { type: 'category', data: data.map(item => item.range) },
        yAxis: { type: 'value', name: '答卷数' },
        series: [
          { name: '答卷数', type: 'bar', data: data.map(item => item.count), itemStyle: { color: '#E6A23C' } }
        ]
      }
      chart.setOption(option)
    }
  }
}
</script>

<style scoped>
.analysis-card {
  margin-bottom: 16px;
}
.card-header {
  font-weight: 600;
}
</style>
